package org.walkerljl.commons.designer;

import org.walkerljl.commons.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EventHandlerGroup<Event> {

    private final TaskStructure<Event> script;

    private List<EventHandler<Event>> eventHandlers;

    EventHandlerGroup(TaskStructure<Event> script,
                      List<EventHandler<Event>> eventHandlers) {
        synchronized (script) {
            assertState(script);
            this.script = script;
            this.eventHandlers = new ArrayList<EventHandler<Event>>(
                    eventHandlers.size());
            CollectionUtils.copy(eventHandlers, this.eventHandlers);
            for (EventHandler<Event> handler : eventHandlers) {
                script.addDependency(handler, null);
            }
        }
    }

    public EventHandlerGroup<Event> then(EventHandler<Event>... eventHandlers) {
        synchronized (script) {
            assertState(script);
            for (EventHandler<Event> from : this.eventHandlers) {
                for (EventHandler<Event> to : eventHandlers) {
                    script.addDependency(from, to);
                }
            }
            for (EventHandler<Event> to : eventHandlers) {
                script.addDependency(to, null);
            }
            this.eventHandlers = new ArrayList<EventHandler<Event>>(
                    eventHandlers.length);
            CollectionUtils.copy(Arrays.asList(eventHandlers), this.eventHandlers);
            return this;
        }
    }

    private void assertState(TaskStructure<Event> script) {
        if (script.isReady()) {
            throw new IllegalStateException(
                    "script is ready, cannot be edit any more.");
        }
    }
}
